//
//  UserInfoViewController.m
//  CoolFM
//
//  Created by 曹曹 on 16/8/29.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "UserInfoViewController.h"
#import "UIView+Frame.h"
#import "AFNetworking.h"
#import "NSString+GX_MD5.h"
#import "CFMacro.h"



@interface UserInfoViewController ()
@property (weak, nonatomic) IBOutlet UITextField *userNickName;
@property (weak, nonatomic) IBOutlet UITextField *userPassword;

@end

@implementation UserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setTitle:@"请填写资料"];
    self.view.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
}

- (IBAction)registAndLoginThen:(id)sender {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        return parameters;
    }];
    
    NSString *passW = [_userPassword.text MD5String32BitsLowercase];
    NSDictionary *sendCode = @{@"password":passW,
                               @"check_code":_checkCode,
                               @"sex":@"0",
                               @"nickname":_userNickName.text,
                               @"user_ip":@"127.0.0.1",
                               @"contact":_contact};
    
    NSDictionary *longin = @{@"password":passW,
                             @"version":@"4.4.0",
                             @"user_ip":@"127.0.0.1",
                             @"contact": _contact};
    
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"159" forHTTPHeaderField:@"Content-Length"];
    [manager.requestSerializer setValue:@"api.kufm.cn" forHTTPHeaderField:@"Host"];
    [manager.requestSerializer setValue:@"ios/4.3.0.0.0/appstore/release" forHTTPHeaderField:@"X-API-ID"];
    [manager.requestSerializer setValue:@"d0ce47483e6728610311619cca3fb195" forHTTPHeaderField:@"X-APP-ID"];
    // 验证输入的验证码
    [manager POST:@"http://api.kufm.cn/v2/user/register"
       parameters:sendCode
         progress:^(NSProgress * _Nonnull uploadProgress) {
         } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             NSLog(@"请求成功:%@", responseObject);
             // 验证码正确时登录
             [manager POST:@"http://api.kufm.cn/v2/user/login"
                parameters:longin
                  progress:^(NSProgress * _Nonnull uploadProgress) {
                      
                  } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                      NSLog(@"请求成功:%@", responseObject);
                      NSDictionary *userDictionary = @{@"user_id": [responseObject[@"data"] objectForKey:@"user_id"],
                                                       @"error_code":responseObject[@"error_code"],
                                                       @"session_id":[responseObject[@"data"] objectForKey:@"session_id"]};
                      /**
                       * 1.登录成功后保存用户信息
                       */
                      NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                      /**
                       * 删除掉之前登录过得用户信息
                       */
                      [user removeObjectForKey:kUser];
                      [user setObject:_userNickName.text forKey:kContact];
                      [user setObject:_userPassword.text forKey:kPassword];
                      /**
                       * 这里需要给初次注册登录的账号一个创建时间
                       */
                      NSString *create_at = [responseObject[@"data"] objectForKey:kcreated_at];
                      [user setObject:create_at forKey:kcreated_at];
                      /**
                       * 发送消息--登陆成功
                       */
                      [[NSNotificationCenter defaultCenter] postNotificationName:@"login"
                                                                          object:@"login"
                                                                        userInfo:userDictionary];
                      // 完成自动登录后跳转到跟视图控制器
                      [self.navigationController popToRootViewControllerAnimated:YES];
                          
                      
                  } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                      NSLog(@"请求失败:%@", error);
                      return;
                  }];
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             NSLog(@"请求失败:%@", error);
         }];
}



- (void)addPromptLabelWithTitle:(NSString *)title {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, -20, self.view.gx_width, 20)];
    label.text = title;
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:12];
    label.gx_centerX = self.view.gx_centerX;
    label.backgroundColor = [UIColor grayColor];
    [self.view addSubview:label];
    // 出现
    [UIView animateWithDuration:0.5 animations:^{
        label.gx_y = 0;
        // 显示2秒
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5 delay:2 options:UIViewAnimationOptionCurveLinear animations:^{
            label.gx_y = -20;
        } completion:^(BOOL finished) {
            
        }];
    }];
}

- (void)viewDidDisappear:(BOOL)animated {
    NSLog(@"销毁");
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
